package cn.wolfcode.shop.cloud.ws;

import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

@Setter
@Getter
@ServerEndpoint("/{uuid}") //相当于RequestMapping("") 资源路径
@Component
public class WebSocketServer {
    private Session session;
    public static ConcurrentHashMap<String,WebSocketServer> clients = new ConcurrentHashMap<>();

    /**
     * 当浏览器和websocket-server建立好连接会执行onOpen方法
     * 当连接中断时会触发OnClose方法,移除关系
     * 当接收到消息会触发onMessage方法
     * onError当出错的时候会触发
     * @param session
     * @param uuid
     */
    @OnOpen
    public void onOpen(Session session, @PathParam( "uuid") String uuid){
        System.out.println("66666666666===>"+uuid);
        this.session = session;
        clients.put(uuid,this);
    }
    @OnClose
    public void onClose(@PathParam( "uuid") String uuid){
        clients.remove(uuid);
    }
    @OnError
    public void onError(Throwable error) {
        error.printStackTrace();
    }

    @OnMessage
    public void onMessage(String msg){
        System.out.println(msg);
    }
}